package org.example.groupwarehouse.service;

import org.example.groupwarehouse.entity.Category;
import org.example.groupwarehouse.mapper.CategoryMapper;
import org.example.groupwarehouse.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zwy
 * @date 2025/5/14下午6:52
 * @className CategoryService
 * @se www.baidu.com
 * @verdion 1.0
 */
@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private GoodsMapper goodsMapper; // 注入GoodsMapper以检查分类下是否有商品

    public List<Category> getAllCategories() {
        return categoryMapper.selectAll();
    }

    public String getCategoryNameById(Integer id) {
        Category category = categoryMapper.findById(id);
        return category != null ? category.getName() : "";
    }
    public boolean addCategory(Category category) {
        // 检查分类名称长度(2-5位)
        if (category.getName().length() < 2 || category.getName().length() > 5) {
            return false;
        }
        // 检查分类名称是否已存在
        Category existing = categoryMapper.getCategoryByName(category.getName());
        if (existing != null) {
            return false;
        }
        // 插入新分类
        return categoryMapper.insertCategory(category) > 0;
    }

    public boolean deleteCategory(Integer id) {
        // 检查分类下是否有商品
        int goodsCount = goodsMapper.countByCategoryId(id);

        System.out.println("goodsCount--- > "+ goodsCount);
        if (goodsCount > 0) {
            return false; // 如果有商品，则不能删除该分类
        }
        // 逻辑删除
        return categoryMapper.updateCategoryStatus(id, 0) > 0;
    }

    // 根据ID查找分类
    public Category findById(Integer id) {
        return categoryMapper.findById(id);
    }

    // 更新分类
    public boolean updateCategory(Category category) {
        return categoryMapper.updateCategory(category) > 0;
    }
}